﻿using UI.Application.Share.Names;
using Prism.Commands;
using Prism.Modularity;
using Prism.Regions;
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Prism.Events;
using UI.Application.Share.Event;
using UI.Application.Share.Model;
using Core.Logger;

namespace Shell.ViewModels
{
    internal class MainWindowViewModel : ReactiveObject
    {
        private IModuleManager ModuleManager { get; }
        private IRegionManager RegionManager { get; }
        private IEventAggregator EventAggregator { get; }

        /// <summary>
        /// 所有硬件是否完成了初始化
        /// </summary>
        public bool IsHardwareInitialized { get; private set; } = false;

        public ICommand LoadedCommand { get; }

        public MainWindowViewModel(IRegionManager regionManager,IModuleManager moduleManager,IEventAggregator eventAggregator)
        {
            RegionManager = regionManager;
            ModuleManager = moduleManager;
            EventAggregator = eventAggregator;
            LoadedCommand = new DelegateCommand(LoadWindow);
            Logs.LogInfo("启动上位机软件");
        }

        private void LoadWindow()
        {
            RegionManager.RequestNavigate(RegionNames.MainRegion, ViewNames.LoginView);
            EventAggregator.GetEvent<LoginSuccessEvent>().Subscribe(LoginSuccess, ThreadOption.UIThread);
            EventAggregator.GetEvent<InitializedSuccessEvent>().Subscribe(() => this.IsHardwareInitialized = true);
        }

        private void LoginSuccess(CurrentUser user)
        {
            if (IsHardwareInitialized)
            {
                //加载主界面
                ModuleManager.LoadModule(ModuleNames.ApplicationMainModule);
                RegionManager.RequestNavigate(RegionNames.MainRegion, ViewNames.MainView);
            }
            else
            {
                ModuleManager.LoadModule(ModuleNames.ApplicationInitializeModule);
                RegionManager.RequestNavigate(RegionNames.MainRegion, ViewNames.InitializeView);
            }
            
        }
    }
}
